// 后台商品管理
const { Good, Tag, Sku } = require("../models/good");
const { Op } = require("sequelize");
const config = require("../config/config");

module.exports = {
  // 增删改查 商品
  getAllGood(req, res) {
    Good.findAll({
      include: [
        {
          model: Tag,
          attributes: ["name"],
        },
        {
          model: Sku,
          attributes: ["name", "amount", "stock_quantity"],
        },
      ],
    }).then((good) => {
      good = JSON.parse(JSON.stringify(good));

      good = good.map((item) => {
        return {
          ...item,
          imageList: JSON.parse(item.imageList),
        };
      });
      res.json({
        code: 200,
        message: "获取成功",
        data: good,
      });
    });
  },
  // 分类分类查询商品
  getFilterGood(req, res) {
    const { name, tagId, price, page, pageSize } = req.body;

    const offset = (page - 1) * pageSize;
    // 构建查询条件
    const whereCondition = {};
    if (name && name.trim() !== "") {
      whereCondition.name = { [Op.like]: `%${name}%` }; // 模糊查询
    }
    if (tagId && tagId !== "") {
      whereCondition.tagId = tagId;
    }
    if (price && price !== "") {
      whereCondition.price = price;
    }
    // 查询总数
    Good.findAndCountAll({
      where: whereCondition,
    }).then((result) => {
      const total = result.count;
      // 分页查询
      Good.findAll({
        include: [
          {
            model: Tag,
            attributes: ["name"],
          },
          {
            model: Sku,
            attributes: ["name", "amount", "stock_quantity"],
          },
        ],
        where: whereCondition,
        limit: pageSize,
        offset: offset,
      }).then((good) => {
        good = JSON.parse(JSON.stringify(good));
        good = good.map((item) => {
          return {
            ...item,
            imageList: JSON.parse(item.imageList),
          };
        });
        res.json({
          code: 200,
          message: "查询成功",
          data: {
            good,
            total,
          },
        });
      });
    });
  },
  // 根据id查询商品
  getGoodById(req, res) {
    const { id } = req.params;
    Good.findOne({
      where: {
        id: id,
      },
      include: [
        {
          model: Tag,
          attributes: ["name"],
        },
        {
          model: Sku,
          attributes: ["name", "amount", "stock_quantity", "id"],
        },
      ],
    }).then((good) => {
      good = JSON.parse(JSON.stringify(good));
      if (good && good.imageList) {
        good.imageList = JSON.parse(good.imageList);
      }

      res.json({
        code: 200,
        message: "获取成功",
        data: good,
      });
    });
  },
  // 新增商品
  createGood(req, res) {
    let {
      name,
      introduction,
      imageList,
      skus,
      tagId,
      isRecommend,
      stock_quantity,
      price,
      avatar,
    } = req.body;
    // 将image序列化
    imageList = JSON.stringify(imageList);
    Good.create({
      name: name,
      introduction: introduction,
      imageList: imageList,
      tagId: tagId,
      isRecommend: isRecommend,
      price: price,
      stock_quantity: stock_quantity,
      avatar: avatar,
    }).then((good) => {
      skus.forEach((item) => {
        Sku.create({
          name: item.name,
          amount: item.amount,
          stock_quantity: item.stock_quantity,
          goodId: good.id,
        });
      });
      res.json({
        code: 200,
        message: "添加成功",
        data: good,
      });
    });
  },
  // 修改商品
  updateGood(req, res) {
    const { id } = req.params;
    let {
      name,
      introduction,
      imageList,
      skus,
      tagId,
      isRecommend,
      avatar,
      price,
      stock_quantity,
    } = req.body;
    imageList = JSON.stringify(imageList);
    Good.update(
      {
        name: name,
        introduction: introduction,
        imageList: imageList,
        tagId: tagId,
        isRecommend: isRecommend || false,
        avatar: avatar,
        price: price,
        stock_quantity: stock_quantity,
      },
      {
        where: {
          id: id,
        },
      }
    ).then((good) => {
      if (skus) {
        Sku.destroy({
          where: {
            goodId: id,
          },
        }).then(() => {
          skus.forEach((item) => {
            Sku.create({
              name: item.name,
              amount: item.amount,
              stock_quantity: item.stock_quantity,
              goodId: id,
            });
          });
          res.json({
            code: 200,
            message: "修改成功",
            data: good,
          });
          return;
        });
      } else {
        res.json({
          code: 200,
          message: "修改成功",
          data: good,
        });
      }
    });
  },
  // 删除商品
  deleteGood(req, res) {
    const { id } = req.params;
    Good.destroy({
      where: {
        id: id,
      },
    }).then((good) => {
      res.json({
        code: 200,
        message: "删除成功",
        data: good,
      });
    });
  },

  //tags增删改查
  getAllTag(req, res) {
    Tag.findAll().then((tag) => {
      res.json({
        code: 200,
        message: "获取成功",
        data: tag,
      });
    });
  },
  getTagById(req, res) {
    const { id } = req.params;
    Tag.findOne({
      where: {
        id: id,
      },
    }).then((tag) => {
      res.json({
        code: 200,
        message: "获取成功",
        data: tag,
      });
    });
  },
  createTag(req, res) {
    const { name } = req.body;
    Tag.create({
      name: name,
    }).then((tag) => {
      res.json({
        code: 200,
        message: "添加成功",
        data: tag,
      });
    });
  },
  updateTag(req, res) {
    const { id } = req.params;
    const { name } = req.body;
    Tag.update(
      {
        name: name,
      },
      {
        where: {
          id: id,
        },
      }
    ).then((tag) => {
      res.json({
        code: 200,
        message: "修改成功",
        data: tag,
      });
    });
  },
  deleteTag(req, res) {
    const { id } = req.params;
    Tag.destroy({
      where: {
        id: id,
      },
    }).then((tag) => {
      res.json({
        code: 200,
        message: "删除成功",
        data: tag,
      });
    });
  },
  // 图片上传
  imageListUpload(req, res) {
    if (!req.file) {
      return res.status(400).send("No file uploaded.");
    }

    let host = config.host.url + ":" + config.host.port;
    res.json({
      code: 200,
      msg: "上传成功",
      data: host + "/public/images/" + req.file.filename,
    });
  },

  // 根据tagId查询商品
  getGoodByTagId(req, res) {
    const { tagId } = req.params;
    Good.findAll({
      where: {
        tagId: tagId,
      },
      include: [
        {
          model: Tag,
          attributes: ["name"],
        },
        {
          model: Sku,
          attributes: ["name", "amount", "stock_quantity"],
        },
      ],
    }).then((good) => {
      good = JSON.parse(JSON.stringify(good));
      good = good.map((item) => {
        return {
          ...item,
          imageList: JSON.parse(item.imageList),
        };
      });
      res.json({
        code: 200,
        message: "获取成功",
        data: good,
      });
    });
  },
  // 根据id查询sku
  getSkuById(req, res) {
    const { id } = req.params;
    Sku.findOne({
      where: {
        id: id,
      },
    }).then((sku) => {
      res.json({
        code: 200,
        message: "获取成功",
        data: sku,
      });
    });
  },
};
